import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/material.dart';
import 'package:fate_blind_box/widget/date_picker/flutter_datetime_picker.dart';

import 'fate_list.dart';

class FateLineUi extends StatelessWidget {
  const FateLineUi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _FateLineUi();
  }
}

class _FateLineUi extends StatefulWidget {
  const _FateLineUi({Key? key}) : super(key: key);

  @override
  State<_FateLineUi> createState() => _FateLineUiState();
}

class _FateLineUiState extends State<_FateLineUi> {
  var _screenWidth = 0.0;
  var _screenHeight = 0.0;

  @override
  Widget build(BuildContext context) {
    final _size = MediaQuery.of(context).size;
    _screenWidth = _size.width;
    _screenHeight = _size.height;
    return AppWidget.navTitleBar(
      title: "月老牵线",
      childWidget:buildContent(),
    );
  }

  final GlobalKey<FormState> _formKey = GlobalKey();
  final _textController = List.generate(4, (index) => TextEditingController());
  Widget buildContent() {
    final List<String> keys = ["设定最少人数", "设定最多人数",  ];
    final List<String> hints = [
      "请输入最少人数6~60人",
      "请输入最多人数6~60人",
    ];
    final List<Widget> formItems = [];
    for (var i = 0; i < keys.length; i++) {
      formItems.add(getFormItem(keys[i], hints[i], i));
    }
    formItems.add(getDateItem("设定牵线开始时间", "请选择活动开始时间", 2));
    formItems.add(getDateItem("设定牵线结束时间", "请选择活动结束时间", 3));

    formItems.add(getSubmitBtn());
    return Form(
      key: _formKey,
      child: Column(children: formItems),
    );
  }

  Widget getDateItem(String key, String hint, int index) {
    return GestureDetector(
      onTap: () {
        final cur = DateTime.now();
        DatePicker.showDatePicker(context,
            showTitleActions: true,
            minTime: DateTime(cur.year, cur.month, cur.day),
            maxTime: DateTime(2099, 12, 31),
            onChanged: (date) {  },
            onConfirm: (date) {
              _textController[index].text = date.toString().substring(0, 19);
            }, currentTime: DateTime.now(), locale: LocaleType.zh);
      },
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 12),
        height: 52,
        width: _screenWidth - 24,
        decoration: BoxDecoration(
            border: Border(
                bottom: BorderSide(width: 1, color: ThemeColor.dividerColor))),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              key,
              style: TextStyle(color: ThemeColor.textColor),
            ),
            Expanded(
              child: TextField(
                enabled: false,
                controller: _textController[index],
                decoration: InputDecoration(
                  hintText: hint,
                  hintStyle: TextStyle(color: ThemeColor.textColorSecond),
                  enabled: false,
                  border: InputBorder.none,
                ),
                textAlign: TextAlign.right,

              )
            ),
            const SizedBox(width: 8,),
            Icon(Icons.arrow_forward_ios, color: ThemeColor.textColorSecond, size: 14,)
          ],
        ),
      ),
    );
  }

  Widget getFormItem(String key, String hint, int index) {
    return Container (
      margin: const EdgeInsets.symmetric(horizontal: 12),
      height: 52,
      width: _screenWidth - 24,
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(width: 1, color: ThemeColor.dividerColor))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            key,
            style: TextStyle(color: ThemeColor.textColor),
          ),
          SizedBox(
            width: 180,
            child: TextFormField(
              controller: _textController[index],
              decoration: InputDecoration(
                hintText: hint,
                hintStyle:
                TextStyle(color: ThemeColor.textColorSecond, fontSize: 14),
                enabledBorder: const UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.transparent)),
                focusedBorder: const UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.transparent)),
              ),
              textAlign: TextAlign.right,
            ),
          )
        ],
      ),
    );
  }

  Widget getSubmitBtn() {
    return GestureDetector(
      onTap: () {
        if(_formKey.currentState?.validate() == true) {
          _formKey.currentState?.save();
          var flag = false;
          for (var element in _textController) {
            if (element.text.isEmpty) {
              flag = true;
            }
          }
          if (flag) {
            ThemeSnackBar.show(context, "请完善信息");
          } else {
            loading(() async {
              await _publish();
            });
          }
        }

      },
      child: Container(
        height: 52,
        margin: const EdgeInsets.fromLTRB(12, 120, 12, 48),
        decoration: ShapeDecoration(
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
            color: ThemeColor.mainColor),
        alignment: Alignment.center,
        child: const Text(
          "发布",
          style: TextStyle(color: Colors.white, fontSize: 16),
        ),
      ),
    );
  }

  _publish() async{
    final minNum = int.parse(_textController[0].text);
    final maxNum = int.parse(_textController[1].text);
    final startTime = _textController[2].text;
    final endTime = _textController[3].text;
    if (minNum < 0 || maxNum < 0) {
      ThemeSnackBar.show(context, "人数不可小于1");
      return;
    }
    if (minNum > maxNum) {
      ThemeSnackBar.show(context, "最大人数不可小于最小人数");
      return;
    }

    final res = await Api.getInstance().publishFateLine(
      int.parse(_textController[0].text),
      int.parse(_textController[1].text),
      _textController[2].text,
      _textController[3].text
    );
    if (res['code'] == 0) {
      Navigator.of(context).push(MaterialPageRoute(builder: (ctx) => const FateListUi()));
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }
}
